package com.ustc.hewei.blogmodule.serviceImpl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ustc.hewei.commonmodule.dto.Result;
import com.ustc.hewei.commonmodule.dto.ScrollResult;
import com.ustc.hewei.commonmodule.dto.UserDTO;
import com.ustc.hewei.commonmodule.entity.Blog;
import com.ustc.hewei.commonmodule.entity.Follow;
import com.ustc.hewei.commonmodule.entity.User;
import com.ustc.hewei.commonmodule.mapper.BlogMapper;
import com.ustc.hewei.commonmodule.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ustc.hewei.commonmodule.service.IFollowService;
import com.ustc.hewei.commonmodule.service.IUserService;
import com.ustc.hewei.nettyrpc2_0.common.annotation.AutowireService;
import com.ustc.hewei.nettyrpc2_0.common.annotation.RPCService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.*;
import java.util.stream.Collectors;

import static com.ustc.hewei.blogmodule.utils.Constants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hewei
 * @since 2022-10-05
 */
@Service
@RPCService(value = IBlogService.class)
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    public IUserService userService;
    @Resource
    private IFollowService followService;

//    public IUserService getUserService() {
//        return userService;
//    }
//
//    public void setUserService(IUserService userService) {
//        this.userService = userService;
//    }

    @Override
    public Result queryBlogById(Long id, UserDTO userDTO) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在!");
        }
        queryLikesByBlog(blog, userDTO);
        queryUserByBlog(blog);
        return Result.ok(blog);
    }

    public void queryUserByBlog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    public void queryLikesByBlog(Blog blog, UserDTO userDTO) {
        if (userDTO == null) {
            blog.setIsLike(false);
        } else {
            Long userId = userDTO.getId();
            String key = BLOG_LIKE_KEY + blog.getId();
            Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
            blog.setIsLike(score != null);
        }
    }

    @Override
    public Result queryHotBlog(Integer current, UserDTO userDTO) {
        List<Blog> hotBlogs = query().orderByDesc("liked")
                .page(new Page<>(current, MAX_PAGE_SIZE)).getRecords();
        hotBlogs.forEach(blog -> {
            queryUserByBlog(blog);
            queryLikesByBlog(blog, userDTO);
        });
        return Result.ok(hotBlogs);
    }

    @Override
    public Result likeBlog(Long id, UserDTO userDTO) {
        String key = BLOG_LIKE_KEY + id;
        Long userId = userDTO.getId();
        // sorted-Set没有isMember方法，只能用查对应元素分数的方法来进行判断
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKE_KEY + id;
        Set<String> top = stringRedisTemplate.opsForZSet().range(key, 0, MAX_LIKED_COUNT);
        if (top == null || top.size() == 0) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top.stream().map(Long::valueOf).collect(Collectors.toList());
        return userService.queryUserDTOByIds(ids);
    }

    @Override
    public Result saveBlog(Blog blog, UserDTO userDTO) {
        Long userId = userDTO.getId();
        blog.setUserId(userId);
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("保存博文失败!");
        }
        // 获取关注当前用户的所有用户，实现信息流的推模式
        List<Follow> followUsers = followService.query().eq("follow_user_id", userId).list();
        for (Follow followUser : followUsers) {
            Long targetId = followUser.getUserId();
            String key = FEED_KEY + targetId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset, UserDTO userDTO) {
        if (userDTO == null) {
            return Result.fail("请先登录!");
        }
        String key = FEED_KEY + userDTO.getId();
        Set<ZSetOperations.TypedTuple<String>> blogIdTuple = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, QUERY_BLOG_COUNT);
        if (blogIdTuple == null || blogIdTuple.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(blogIdTuple.size());
        long time = 0;
        int resOffset = 0;
        for (ZSetOperations.TypedTuple<String> tuple : blogIdTuple) {
            ids.add(Long.valueOf(tuple.getValue()));
            long score = tuple.getScore().longValue();
            if (time == score) {
                ++resOffset;
            } else {
                time = score;
                resOffset = 1;
            }
        }
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids)
                .last("ORDER BY FIELD(id, " + idStr + ")").list();
        ScrollResult scrollResult = new ScrollResult();
        for (Blog blog : blogList) {
            queryUserByBlog(blog);
            queryLikesByBlog(blog, userDTO);
        }
        scrollResult.setList(blogList).setOffset(resOffset).setMinTime(time);
        return Result.ok(scrollResult);
    }

    @Override
    public Result queryMyBlog(Integer current, UserDTO userDTO) {
        if (userDTO == null) {
            return Result.ok(Collections.emptyList());
        }
        Long userID = userDTO.getId();
        List<Blog> blogList = query().eq("user_id", userID)
                .page(new Page<>(current, MAX_PAGE_SIZE)).getRecords();
        return Result.ok(blogList);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long userId) {
        List<Blog> blogList = query().eq("user_id", userId).page(new Page<>(current, MAX_PAGE_SIZE)).getRecords();
        return Result.ok(blogList);
    }
}